package se.sweco.ws.impl;

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.TimerTask;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import se.sweco.ws.DataStore;

public class TrelocityDataTask extends TimerTask {
	/* FIXME: What should default update interval be? 30 minutes? */
	public static final long DEFAULT_INTERVAL_MS = 1000 * 60 * 30;
	private static final String XML_URL = "http://stockholm.trelocity.se/xml?key=k8zy97aqjhs5z7n8";
	
	private DataStore storage;
	private XMLReader parser;

	public TrelocityDataTask(DataStore storage) {
		this.storage = storage;
		try {
			parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
		} catch (SAXException e) {
			System.err.println(e.getMessage());
		}
	}

	@Override
	public void run() {
		/* NOTE: This runs in a separate thread */
		
		URL url = null;
		HttpURLConnection conn = null;

		try {
			url = new URL(XML_URL);
			
			conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			
			TrelocityContentHandler handler = new TrelocityContentHandler(storage.getRoutes());
			parser.setContentHandler(handler);
			InputSource source = new InputSource(conn.getInputStream());
			parser.parse(source);
			
			storage.clearTrafficData();
			storage.addTrafficData(handler.getData());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
}
